import random
import os
import json


BankName = '中国农业银行'
MaxUser = 100
#存储账户
user_db = {}   # {账户: 用户信息}
address_db = {}   #  {账户: 地址信息}

#初始化数据
def init_system():
    global user_db, address_db
    if os.path.exists('user_db.json'):
        with open('user_db.json', 'r') as f:
            user_db = json.load(f)
    if os.path.exists('address_db.json'):
        with open('address_db.json', 'r') as f:
            address_db = json.load(f)



#保存数据
def save_data():
    with open('user_db.json', 'w') as f:
        json.dump(user_db, f)
    with open('address_db.json', 'w') as f:
        json.dump(address_db, f)



#用户账号
def get_account_number():
    #生成8位唯一账号
    while True:
        account_num = str(random.randint(10000000, 99999999))
        if account_num not in user_db:
            return account_num

#创建账户
def create_account(name, account_type, password, country, street, province, initial_balance = 0):
    if len(user_db) >= MaxUser:
        return 3
    #开户
    account_num = get_account_number()

    #存储用户信息
    user_db[account_num] = {
        'account_num': account_num,
        'account_type': account_type,
        'name': name,
        'password': password,
        'balance': initial_balance,
        'bank_name': BankName
    }
    #存储地址信息
    address_db[account_num] = {
        'country': country,
        'street': street,
        'province': province
    }
    save_data()
    return 1
#存钱
def deposit(account_num, amount):
    if account_num not in user_db:
        return False
    user_db[account_num]['balance'] += amount
    save_data()
    return True

#取钱
def draw(account_num, password, amount):
    if account_num not in user_db:
        return 1
    if str(user_db[account_num]['password']) != str(password):
        return 2
    if user_db[account_num]['balance'] < amount:
        return 3
    user_db[account_num]['balance'] -= amount
    save_data()
    return 0

#转账
def transfer(from_count, to_count, password, amount):
    if from_count not in user_db or to_count not in user_db:
        return 1
    if str(user_db[from_count]['password']) != str(password):
        return 2
    if user_db[from_count]['balance'] < amount:
        return 3
    user_db[from_count]['balance'] -= amount
    user_db[to_count]['balance'] += amount
    save_data()
    return 0

#查询账户
def query_account(account_num, password):
    if account_num not in user_db:
        print("该用户不存在")
        return
    if str(user_db[account_num]['password']) != str(password):
        print("密码错误")
        return

    user = user_db[account_num]
    addre = address_db.get(account_num, {})

    print("\n=========账户信息========")
    print(f"当前账号: {user['account_num']}")
    print(f"密码: {user['password']}")
    print(f"余额: {user['balance']}")
    print(f"用户居住地址: {addre.get('country','')}, {addre.get('province','')}, {addre.get('street','')}")
    print(f"当前用户的开户行: {user['bank_name']}")
    print("\n=======================")


def show_main():
    init_system()
    while True:
        action = input("*************************"
                       "\n*  中国农业银行账户管理系统  *"
                       "\n*************************"
                       "\n*          选项          *"
                       "\n*         1.开户         *"
                       "\n*         2.存钱         *"
                       "\n*         3.取钱         *"
                       "\n*         4.转账         *"
                       "\n*         5.查询         *"
                       "\n*         6.Bye         *"
                       "\n*************************"
                       "\n请选择功能: ")
        if action == '1':
            #开户
            name = input("姓名: ")
            account_type = int(input("选择账户类型（1-【金卡】，2-【普通卡】）: "))
            password =input("输入密码: ")
            country = input("国家: ")
            province = input("省份: ")
            street = input("街道: ")
            balance = int(input("金额: "))

            result = create_account(name, account_type, password, country, province, street, balance)
            if result == 1:
                print("开户成功")
            elif result == 2:
                print("用户已存在")
            else:
                print("用户库已满")
        #存钱
        elif action == '2':
            account_num = input("输入账号:")
            amount = int(input("存取金额: "))

            if deposit(account_num, amount):
                print("存款成功")
            else:
                print("账号不存在")
        #取钱
        elif action =='3':
            account_num = input("输入账号: ")
            password = input("输入密码: ")
            amount =int(input("取款金额: "))

            result = draw(account_num, password, amount)
            if result == 1:
                print("账户不存在")
            elif result == 2:
                print("密码不对")
            else:
                print("钱不够")
        #转账
        elif action == '4':
            from_count = input("转出账号: ")
            to_count = input("转入账账号: ")
            password = input("转出账户密码: ")
            amount = int(input("转账金额: "))

            result = transfer(from_count, to_count, password, amount)
            if result == 0:
                print("转账成功")
            elif result == 1:
                print("账户不存在")
            elif result == 2:
                print("密码错误")
            else:
                print("金额不足")
        #查询
        elif action == '5':
            account_num = input("账号: ")
            password = input("密码: ")
            query_account(account_num, password)

        #Bye
        elif action == '6':
            print("感谢使用，再见。")
            break
        else:
            print("输入错误")

if __name__ == '__main__':
    show_main()






